//
//  ViewController.m
//  client
//
//  Created by ld on 2017/6/27.
//
//

#import "HomeViewController.h"
#import "Masonry.h"
#import "WebViewJavascriptBridge.h"
#import "WechatPayHelper.h"
#import "AliPayHelper.h"
#import "AMapLocationHelper.h"
#import "Constant.h"
#import "JYNavigationBarRightView.h"

#define kNavigationBarColor ([UIColor colorWithRed:0.0f green:64.0f/255.0f blue:152.0f/255.0f alpha:1.0f])

@interface HomeViewController () <UIWebViewDelegate>

@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *saveButton;
@property (nonatomic, strong) UIImageView *iconImageView;

@property (nonatomic, strong) UIWebView *webview;

@property (nonatomic, copy) NSArray *nameList;
@property (nonatomic, copy) NSArray *directoryList;

@property (nonatomic, copy) NSArray *NavigationBarHiddenUrlList;
@property (nonatomic, copy) NSArray *tabBarHiddenUrlList;
@property (nonatomic, copy) NSArray *backButtonHiddenUrlList;
@property (nonatomic, copy) NSArray *iconImageViewHiddenUrlList;

@property (nonatomic, strong) WebViewJavascriptBridge *bridge;

@end

@implementation UIWebView (alert)

- (void)webView:(UIWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(id)frame {

    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:message message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];

    [alertView show];
}

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 高德地图定位
    // [AMapLocationHelper getLocation];
    
    // 设置背景色
    [self.view setBackgroundColor:[UIColor whiteColor]];
    // 不自动调整子视图的位置
    [self setAutomaticallyAdjustsScrollViewInsets:NO];
    
    // 设定导航栏
    [self resetNavigationBar];
    
    // 添加webview
    [self.view addSubview:self.webview];
    [self.webview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(64, 0, 49, 0));
    }];
    
    // 加载H5
    NSURL *url = [[NSBundle mainBundle] URLForResource:self.nameList[self.menuItem] withExtension:@"" subdirectory:self.directoryList[self.menuItem]];
    [self.webview loadRequest:[NSURLRequest requestWithURL:url]];
    
    self.bridge = [WebViewJavascriptBridge bridgeForWebView:self.webview];
    [self.bridge setWebViewDelegate:self];
    [self.bridge registerHandler:@"startPhonePay" handler:^(id data, WVJBResponseCallback responseCallback) {

        NSLog(@"startPhonePay called with: %@", data);
        
        NSDictionary *dict = @{
                               @"subject"       : data[@"out_trade_no"],
                               @"out_trade_no"  : data[@"out_trade_no"],
                               @"total_amount"  : data[@"money"]
                               };
        
        [AliPayHelper pay:dict completion:^(NSDictionary *resultDic) {

            NSString *resultStatus = resultDic[@"resultStatus"];
            NSString *memo = resultDic[@"memo"];
            
            if (memo.length == 0) {
                if ([resultStatus isEqualToString:@"9000"]) {
                    memo = @"订单支付成功";
                } else if ([resultStatus isEqualToString:@"8000"]) {
                    memo = @"正在处理中，支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态";
                } else if ([resultStatus isEqualToString:@"4000"]) {
                    memo = @"订单支付失败";
                } else if ([resultStatus isEqualToString:@"5000"]) {
                    memo = @"重复请求";
                } else if ([resultStatus isEqualToString:@"6001"]) {
                    memo = @"用户中途取消";
                } else if ([resultStatus isEqualToString:@"6002"]) {
                    memo = @"网络连接出错";
                } else if ([resultStatus isEqualToString:@"6004"]) {
                    memo = @"支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态";
                } else {
                    memo = @"其它支付错误";
                }
            }
            
            NSDictionary *responseDict = @{
                                           @"result"  : resultStatus,
                                           @"message" : memo
                                           };
            if ([resultStatus isEqualToString:@"9000"]) {
                responseDict = @{
                                 @"result"  : @"1",
                                 @"message" : memo
                                 };
            }
            
            [self.bridge callHandler:@"finishPhonePay_ali" data:responseDict responseCallback:^(id responseData) {
            }];
        }];
    }];
    [self.bridge registerHandler:@"startWeiChatPay" handler:^(id data, WVJBResponseCallback responseCallback) {

        NSLog(@"startPhonePay called with: %@", data);
        [WechatPayHelper pay:@{ @"prepayid" : data[@"prepayid"] }];
    }];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kWechatPayFinishNotification object:nil];
}

#pragma mark - target action

- (void)back:(UIButton *)button {
    
    if (self.webview.canGoBack) {
        
        [self.webview goBack];
    } else {
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)save:(UIButton *)button {
    
    NSLog(@"save");
    [self.bridge callHandler:@"save" data:nil responseCallback:^(id responseData) {
    }];
}

- (void)wechatPayFinish:(NSNotification *)notification {
    
    if ([self.webview.request.URL.absoluteString rangeOfString:@"price_detail.html"].location != NSNotFound) {
        
        [self.bridge callHandler:@"finishPhonePay" data:notification.userInfo responseCallback:^(id responseData) {
            
            NSLog(@"ObjC received response: %@", responseData);
        }];
    }
}

#pragma mark - UI

- (void)resetNavigationBar {
    
    // 返回按钮
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(-10, 0, 50, 30)];
    [backButton setHidden:YES];
    [backButton setTitle:@"返回" forState:UIControlStateNormal];
    [backButton setTitle:@"返回" forState:UIControlStateSelected];
    [backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [backButton.titleLabel setFont:[UIFont systemFontOfSize:14.0f]];
    [backButton setImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [backButton setImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateHighlighted];
    [backButton addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    
    // 标题
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 120, 30)];
    titleLabel.font = [UIFont systemFontOfSize:16.0f];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.numberOfLines = 1;
    
    // 导航栏右侧
    JYNavigationBarRightView *rightView = [[JYNavigationBarRightView alloc] init];
    rightView.handler = ^{
        
        [self save:nil];
    };
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.titleView = titleLabel;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightView];
    
    self.backButton = backButton;
    self.titleLabel = titleLabel;
    self.saveButton = rightView.saveButton;
    self.iconImageView = rightView.iconImageView;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    // 状态栏设定
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    // 导航栏设定
    [self.navigationController.navigationBar setBarTintColor:kNavigationBarColor];
    [self.navigationController setNavigationBarHidden:NO];
    // tabBar设定
    [self.tabBarController.tabBar setHidden:NO];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wechatPayFinish:) name:kWechatPayFinishNotification object:nil];
}

#pragma mark - getter

- (UIWebView *)webview {
    if (!_webview) {
        _webview = [[UIWebView alloc] init];
        _webview.delegate = self;
    }
    return _webview;
}

- (NSArray *)nameList {
    
    if (!_nameList) {
        
        _nameList = @[
                      @"select_track.html",
                      @"order_list.html",
                      @"me.html"
                      ];
    }
    
    return _nameList;
}

- (NSArray *)directoryList {
    
    if (!_directoryList) {
        
        _directoryList = @[
                           @"html/customer/order",
                           @"html/customer/order",
                           @"html/customer/me"
                           ];
    }
    
    return _directoryList;
}

- (NSArray *)NavigationBarHiddenUrlList {
    
    if (!_NavigationBarHiddenUrlList) {
        
        _NavigationBarHiddenUrlList = @[
                                        @"login.html",
                                        @"sign.html",
                                        @"forgot.html",
                                        @"order_list.html",
                                        @"me.html"
                                        ];
    }
    
    return _NavigationBarHiddenUrlList;
}

- (NSArray *)tabBarHiddenUrlList {
    
    if (!_tabBarHiddenUrlList) {
        
        _tabBarHiddenUrlList = @[
                                 @"login.html",
                                 @"sign.html",
                                 @"forgot.html"
                                 ];
    }
    
    return _tabBarHiddenUrlList;
}

- (NSArray *)backButtonHiddenUrlList {
    
    if (!_backButtonHiddenUrlList) {
        
        _backButtonHiddenUrlList = @[
                                 @"select_track.html"
                                 ];
    }
    
    return _backButtonHiddenUrlList;
}

- (NSArray *)iconImageViewHiddenUrlList {
    
    if (!_iconImageViewHiddenUrlList) {
        
        _iconImageViewHiddenUrlList = @[
                                     @"order_ok.html"
                                     ];
    }
    
    return _iconImageViewHiddenUrlList;
}

#pragma mark - UIWebViewDelegate

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    
    self.titleLabel.text = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    self.titleLabel.text = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    
    NSString *destURL = request.URL.absoluteString;
    
    // 马上订单
    if (self.menuItem == MenuItemHome) {
        
        
    } else if (self.menuItem == MenuItemOrder) { // 我的订单
        
        if ([destURL rangeOfString:@"select_track.html"].location != NSNotFound) {
            
            NSURL *url = [[NSBundle mainBundle] URLForResource:self.nameList[self.menuItem] withExtension:@"" subdirectory:self.directoryList[self.menuItem]];
            [self.webview loadRequest:[NSURLRequest requestWithURL:url]];
        }
    } else if (self.menuItem == MenuItemMe) { // 我的
        
        if ([destURL rangeOfString:@"select_track.html"].location != NSNotFound) {
            
            NSURL *url = [[NSBundle mainBundle] URLForResource:self.nameList[self.menuItem] withExtension:@"" subdirectory:self.directoryList[self.menuItem]];
            [self.webview loadRequest:[NSURLRequest requestWithURL:url]];
        }
    }
    
    [self resetNavigationBarAndTabBarWithRequest:request];
    
    return YES;
}

#pragma mark - Private

- (void)resetNavigationBarAndTabBarWithRequest:(NSURLRequest *)request {

    NSString *destURL = request.URL.absoluteString;
    
    if ([destURL isEqualToString:@"about:blank"]) {
        return;
    }
    
    BOOL navigationBarHidden = [self navigationBarHidden:destURL];
    BOOL tabBarHidden = [self tabBarHidden:destURL];
    
    self.navigationController.navigationBar.hidden = navigationBarHidden;
    self.backButton.hidden = [self backButtonHidden:destURL];
    self.iconImageView.hidden = [self iconImageViewHidden:destURL];
    self.saveButton.hidden = !self.iconImageView.hidden;
    
    self.tabBarController.tabBar.hidden = tabBarHidden;
    
    [self.webview mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(navigationBarHidden ? 20 : 64, 0, tabBarHidden ? 0 : 49, 0));
    }];
}

- (BOOL)navigationBarHidden:(NSString *)url {
    
    __block BOOL hidden = NO;

    // 马上订单
    if (self.menuItem == MenuItemHome) {
        
        
    } else if (self.menuItem == MenuItemOrder) { // 我的订单
        
        if ([url rangeOfString:@"order_list.html"].location != NSNotFound) {
            
            hidden = YES;
            return hidden;
        }
    } else if (self.menuItem == MenuItemMe) { // 我的
        
        if ([url rangeOfString:@"me.html"].location != NSNotFound) {
            
            hidden = YES;
            return hidden;
        }
    }

    [self.NavigationBarHiddenUrlList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

        if ([url rangeOfString:obj].location != NSNotFound) {
        
            hidden = YES;
            *stop = YES;
        }
    }];

    return hidden;
}

- (BOOL)tabBarHidden:(NSString *)url {
    
    __block BOOL hidden = NO;
    
    // 马上订单
    if (self.menuItem == MenuItemHome) {
        
        if ([url rangeOfString:@"select_track.html"].location != NSNotFound) {
            
            hidden = NO;
            return hidden;
        } else {
            
            hidden = YES;
            return hidden;
        }
    } else if (self.menuItem == MenuItemOrder) { // 我的订单
        
        if ([url rangeOfString:@"order_list.html"].location != NSNotFound ||
            [url rangeOfString:@"order_detail.html"].location != NSNotFound ||
            [url rangeOfString:@"order_trace.html"].location != NSNotFound ||
            [url rangeOfString:@"price_detail.html"].location != NSNotFound) {
            
            hidden = NO;
            return hidden;
        } else {
            
            hidden = YES;
            return hidden;
        }
    } else if (self.menuItem == MenuItemMe) { // 我的
        
        
    }

    [self.tabBarHiddenUrlList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if ([url rangeOfString:obj].location != NSNotFound) {
            
            hidden = YES;
            *stop = YES;
        }
    }];
    
    return hidden;
}

- (BOOL)backButtonHidden:(NSString *)url {
    
    __block BOOL hidden = NO;
    
    // 马上订单
    if (self.menuItem == MenuItemHome) {
        
        
    } else if (self.menuItem == MenuItemOrder) { // 我的订单
        
        
    } else if (self.menuItem == MenuItemMe) { // 我的
        
        
    }

    [self.backButtonHiddenUrlList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if ([url rangeOfString:obj].location != NSNotFound) {
            
            hidden = YES;
            *stop = YES;
        }
    }];
    
    return hidden;
}

- (BOOL)iconImageViewHidden:(NSString *)url {
    
    __block BOOL hidden = NO;
    
    // 马上订单
    if (self.menuItem == MenuItemHome) {
        
        
    } else if (self.menuItem == MenuItemOrder) { // 我的订单
        
        
    } else if (self.menuItem == MenuItemMe) { // 我的
        
        
    }
    
    [self.iconImageViewHiddenUrlList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if ([url rangeOfString:obj].location != NSNotFound) {
            
            hidden = YES;
            *stop = YES;
        }
    }];
    
    return hidden;
}

@end
